const {
  $util,
} = getApp();

Page({
  data: {
    page: 1,
    list: [],
  },
  onLoad(ops) {
    this.setData(ops);
    if (ops.typ && ops.typ == 'order') {
      wx.setNavigationBarTitle({
        title: '党费缴费订单',
      });
      this.loadOrderList();
    } else {
      wx.setNavigationBarTitle({
        title: '党费缴纳记录',
      });
      this.loadList();
    }
  },
  onShow() {
    this.setData({
      isSaaS: wx.getStorageSync('isSaaS'),
    });
  },
  loadList() {
    const D = this.data;
    $util.request({
      url: `entry/wxapp/partyman.dues.${D.cateid === '0' ? 'record' : 'manualRecord'}`,
      data: {
        page: D.page,
      },
      success: (res) => {
        let list = res.data;
        if (!this.data.isSaaS) {
          if (D.page > 1) {
            list = [...D.list, ...list];
          }
          this.setData({
            hasMore: list.length < res.total,
          });
        }
        this.setData({
          list,
          loaded: true,
          total: res.total,
        });
      },
    });
  },
  // 缴费订单列表
  loadOrderList() {
    const D = this.data;
    $util.request({
      url: 'entry/wxapp/partyman.dues.orderlist',
      data: {
        page: D.page,
      },
      success: (res) => {
        let list = res.data;
        if (D.page > 1) {
          list = [...D.list, ...list];
        }
        this.setData({
          list,
          loaded: true,
          hasMore: list.length < res.total,
          total: res.total,
        });
      },
    });
  },
  onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({
      page: this.data.page + 1,
    }, () => {
      this.data.typ && this.data.typ == 'order' ? this.loadOrderList() : this.loadList();
    });
  },
  download(e) {
    $util.request({
      url: 'entry/wxapp/partyman.dues.getFeeVoucher',
      data: {
        orderid: e.currentTarget.dataset.id,
      },
      success: (res) => {
        res.errno === 0 && wx.downloadFile({
          url: res.fileurl,
          success: (res) => {
            if (res.statusCode === 200) {
              wx.saveFile({
                tempFilePath: res.tempFilePath,
                success: (result) => {
                  wx.showModal({
                    title: '提示',
                    content: '是否查看电子发票',
                    success: (re) => {
                      if (re.confirm) {
                        wx.openDocument({
                          filePath: result.savedFilePath,
                        });
                      }
                    },
                  });
                },
              });
            }
          },
          fail: (res) => {
            console.log(res);
          },
          complete: (res) => {
            wx.hideLoading();
          },
        });
      },
    });
  },
});
